function test_y = knn(x, y, test_x, k, num)
% x:nxm,y:nx1,test_x:n0xm,test_y:n0x1
n0 = size(test_x, 1);
test_y = zeros(n0, 1);
for i = 1 : n0
    ind = [];
    max_label = 0;
    Dist = sum((x - test_x(i, :)).^2,2);
    % 从小大大排序，取前k个
    [D,I] = sort(Dist);
    D = D(1:k, :);
    D_y = y(I(1:k), :);
    for j = 1 : num
        % 计算k个样本中各类样本的数量,记录下最大数量的样本的类别
        label1 = sum(D_y==j);
        if label1 > max_label
            max_label = label1;
            ind = [];
            ind = [ind; j];
        elseif label1 == max_label
            ind = [ind; j];
        end
    end
    num_ind = size(ind, 1);
    min_dist = inf;
    % 如果存在数量相等的情况,就将距离之和最小的类标签作为test_y的类别
    for j1 = 1 : num_ind
        dist = sum(D(D_y == ind(j1)));
        if dist <= min_dist
            test_y(i, :) = ind(j1);
        end
    end
end
end